package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.enums.InnerAccountEnum;
import com.settlement.system.common.enums.LazyUserLockStatusEnum;
import com.settlement.system.common.enums.MemberEnum;
import com.settlement.system.common.enums.MemberLevelEnum;
import com.settlement.system.common.model.Option;
import com.settlement.system.common.util.MailUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.mapper.SysLazyToolUserMapper;
import com.settlement.system.model.entity.SysLazyToolUser;
import com.settlement.system.model.form.RechargeForm;
import com.settlement.system.model.form.SysLazyToolUserForm;
import com.settlement.system.model.query.SysLazyToolUserQuery;
import com.settlement.system.model.vo.SysLazyToolUserImportVo;
import com.settlement.system.service.SysDictService;
import com.settlement.system.service.SysLazyToolUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 懒人秘籍用户信息表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-12-29
 */
@Service
@RequiredArgsConstructor
public class SysLazyToolUserServiceImpl extends ServiceImpl<SysLazyToolUserMapper, SysLazyToolUser> implements SysLazyToolUserService {

    private final SysDictService sysDictService;

    private final JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromMail;

    @Override
    public Page<SysLazyToolUser> getPage(SysLazyToolUserQuery queryParams) {
        // 通过字典查找出用户等级
        List<Option> optionList = sysDictService.listDictOptions(SystemConstants.MEMBER_LEVEL);
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        Page<SysLazyToolUser> page = new Page<>(pageNum, pageSize);
        Page<SysLazyToolUser> resultPage = this.baseMapper.getPage(page, queryParams);
        if (resultPage.getRecords().size() > 0) {
            resultPage.getRecords().forEach(sysLazyToolUser -> {
                if (MemberEnum.N.getValue().equals(sysLazyToolUser.getMember())) {
                    sysLazyToolUser.setMemberName(MemberEnum.N.getLabel());
                } else {
                    sysLazyToolUser.setMemberName(MemberEnum.Y.getLabel());
                }
                // 置空密码
                sysLazyToolUser.setPassword(null);
                optionList.stream().filter(option -> Integer.parseInt(option.getValue().toString()) == sysLazyToolUser.getMemberLevel()).findFirst().ifPresent(option -> sysLazyToolUser.setMemberLevelName(option.getLabel()));
            });
        }
        return resultPage;
    }

    @Override
    public boolean saveSysLazyToolUser(SysLazyToolUserForm sysLazyToolUserForm) {
        SysLazyToolUser sysLazyToolUser = new SysLazyToolUser();
        BeanUtil.copyProperties(sysLazyToolUserForm, sysLazyToolUser);
        sysLazyToolUser.setCreateTime(null);
        return this.saveOrUpdate(sysLazyToolUser);
    }

    @Override
    public SysLazyToolUserForm getSysLazyToolUserFormData(Long id) {
        SysLazyToolUser sysLazyToolUser = this.getById(id);
        SysLazyToolUserForm sysLazyToolUserForm = new SysLazyToolUserForm();
        BeanUtil.copyProperties(sysLazyToolUser, sysLazyToolUserForm);
        return sysLazyToolUserForm;
    }

    @Override
    public boolean deleteSysLazyToolUser(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
    }

    @Override
    public void importData(List<SysLazyToolUserImportVo> voList) {
        List<SysLazyToolUser> sysLazyToolUserList = new ArrayList<>();
        for (SysLazyToolUserImportVo importVo : voList) {
            SysLazyToolUser sysLazyToolUser = new SysLazyToolUser();
            BeanUtil.copyProperties(importVo, sysLazyToolUser);
            sysLazyToolUserList.add(sysLazyToolUser);
        }
        this.saveOrUpdateBatch(sysLazyToolUserList);
    }

    @Override
    public List<SysLazyToolUserImportVo> findByIds(String idsStr) {
        if (StrUtil.isBlank(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysLazyToolUser> sysLazyToolUserList = this.getBaseMapper().selectBatchIds(ids);
        List<SysLazyToolUserImportVo> voList = new ArrayList<>();
        for (SysLazyToolUser sysLazyToolUser : sysLazyToolUserList) {
            SysLazyToolUserImportVo vo = new SysLazyToolUserImportVo();
            BeanUtil.copyProperties(sysLazyToolUser, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public boolean registerSysLazyToolUser(SysLazyToolUserForm sysLazyToolUserForm) {
        /*Assert.isTrue(StringUtils.isNotEmpty(sysLazyToolUserForm.getCode()), "手机验证码不能为空");
        // 从redis中获取手机号验证码
        Object code = redisTemplate.opsForValue().get(SystemConstants.MOBILE_CODE_CACHE_PREFIX + sysLazyToolUserForm.getMobile());
        Assert.notNull(code, "手机验证码不存在");
        Assert.isTrue(String.valueOf(code).equals(sysLazyToolUserForm.getCode()), "手机验证码错误");*/
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectOne(new LambdaQueryWrapper<SysLazyToolUser>().eq(SysLazyToolUser::getMobile, sysLazyToolUserForm.getMobile()));
        Assert.isTrue(sysLazyToolUser == null, "此手机号码已经注册，请勿重复注册");
        sysLazyToolUser = new SysLazyToolUser();
        BeanUtil.copyProperties(sysLazyToolUserForm, sysLazyToolUser);
        return this.saveOrUpdate(sysLazyToolUser);
    }

    @Override
    public void experience(String appId) {
        // 查找用户
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectOne(new LambdaQueryWrapper<SysLazyToolUser>().eq(SysLazyToolUser::getId, appId));
        Assert.isTrue(sysLazyToolUser.getExperienceDate() == null, "不能重复体验");
        sysLazyToolUser.setExperienceDate(LocalDate.now().plusDays(7));
        this.baseMapper.updateById(sysLazyToolUser);
    }

    @Override
    public SysLazyToolUser loginSysLazyToolUser(SysLazyToolUserForm sysLazyToolUserForm) {
        /*// 校验手机验证码
        Assert.isTrue(StringUtils.isNotEmpty(sysLazyToolUserForm.getCode()), "手机验证码不能为空");
        // 从redis中获取手机号验证码
        Object code = redisTemplate.opsForValue().get(SystemConstants.MOBILE_CODE_CACHE_PREFIX + sysLazyToolUserForm.getMobile());
        Assert.notNull(code, "手机验证码不存在");
        Assert.isTrue(String.valueOf(code).equals(sysLazyToolUserForm.getCode()), "手机验证码错误");*/
        // 查找用户
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectOne(new LambdaQueryWrapper<SysLazyToolUser>().eq(SysLazyToolUser::getMobile, sysLazyToolUserForm.getMobile()));
        Assert.isTrue(sysLazyToolUser != null, "手机号码不存在，请注册");
        Assert.isTrue(sysLazyToolUser.getPassword().equals(sysLazyToolUserForm.getPassword()), "登录密码不正确");
        // 检查是否账号被禁用
        Assert.isTrue(LazyUserLockStatusEnum.Y.getValue().equals(sysLazyToolUser.getLockStatus()), "账号被禁用");
        // 更新设备ID
        sysLazyToolUser.setDeviceId(sysLazyToolUserForm.getDeviceId());
        this.updateById(sysLazyToolUser);
        return sysLazyToolUser;
    }

    @Override
    public void recharge(RechargeForm rechargeForm) {
        // 通过字典查找出用户等级
        List<Option> optionList = sysDictService.listDictOptions(SystemConstants.MEMBER_LEVEL);
        Assert.isTrue(optionList.stream().anyMatch(option -> Integer.parseInt(option.getValue().toString()) == rechargeForm.getMemberLevel()), "会员等级参数错误");
        Option memberLevelOption = optionList.stream().filter(option -> Integer.parseInt(option.getValue().toString()) == rechargeForm.getMemberLevel()).findFirst().orElse(null);
        // 取出会员金额
        String moneyText = memberLevelOption.getRemark();
        Assert.isTrue(StringUtils.isNotEmpty(moneyText), "充值失败");
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectById(rechargeForm.getId());
        // 充值代码 TODO
        LocalDate expireDate;
        // 在原来会员过期时间基础上加上相应的天数
        if (sysLazyToolUser.getMemberExpireDate() == null) {
            expireDate = LocalDate.now();
            sysLazyToolUser.setMemberLevel(MemberLevelEnum.ZERO.getValue());
        } else if (sysLazyToolUser.getMemberExpireDate() != null && sysLazyToolUser.getMemberExpireDate().isBefore(LocalDate.now())) {
            // 如果用户已经到期，会员到期日需要重新计算，不能追加
            expireDate = LocalDate.now();
            sysLazyToolUser.setMemberLevel(MemberLevelEnum.ZERO.getValue());
        } else {
            expireDate = sysLazyToolUser.getMemberExpireDate();
        }
        if (MemberLevelEnum.ONE.getValue().equals(rechargeForm.getMemberLevel())) {
            expireDate = expireDate.plusMonths(1);
        } else if (MemberLevelEnum.TWO.getValue().equals(rechargeForm.getMemberLevel())) {
            expireDate = expireDate.plusMonths(2);
        } else if (MemberLevelEnum.THREE.getValue().equals(rechargeForm.getMemberLevel())) {
            expireDate = expireDate.plusMonths(3);
        } else if (MemberLevelEnum.SIX.getValue().equals(rechargeForm.getMemberLevel())) {
            expireDate = expireDate.plusMonths(6);
        } else if (MemberLevelEnum.ALL.getValue().equals(rechargeForm.getMemberLevel())) {
            expireDate = LocalDate.MAX;
        }
        sysLazyToolUser.setMemberExpireDate(expireDate);
        sysLazyToolUser.setMember(MemberEnum.Y.getValue());
        // 如果用户已经到期，那重新充值后，会员等级不会追加
        if (expireDate.isAfter(LocalDate.now())) {
            sysLazyToolUser.setMemberLevel(rechargeForm.getMemberLevel() + sysLazyToolUser.getMemberLevel());
        } else {
            sysLazyToolUser.setMemberLevel(rechargeForm.getMemberLevel());
        }
        this.saveOrUpdate(sysLazyToolUser);
    }

    @Override
    public void checkCanRunFlow(String userId, String deviceId) {
        SysLazyToolUser lazyToolUser = this.baseMapper.selectById(userId);
        // 检查当前运行脚本的设备是否是当前登录用户，如果不是则不允许运行脚本
        Assert.isTrue(deviceId.equals(lazyToolUser.getDeviceId()), "账号已在其他设备登录或者用户未登录，请重新登录");
        // 检查是否是会员
        if (MemberEnum.Y.getValue().equals(lazyToolUser.getMember())) {
            // 检查会员是否过期
            Assert.isTrue(lazyToolUser.getMemberExpireDate().isAfter(LocalDate.now()) || lazyToolUser.getMemberExpireDate().equals(LocalDate.now()), "会员已经过期，请重新充值");
        } else {
            if (lazyToolUser.getExperienceDate() == null) {
                lazyToolUser.setExperienceDate(LocalDate.now().plusDays(7));
                this.saveOrUpdate(lazyToolUser);
            } else {
                Assert.isTrue(lazyToolUser.getExperienceDate().isAfter(LocalDate.now()) || lazyToolUser.getExperienceDate().equals(LocalDate.now()), "体验7天已经到期，请充值");
            }
        }
    }

    @Override
    public void findPwd(String mobile, String email) {
        // 检查手机号码绑定的邮箱是否正确
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectOne(new LambdaQueryWrapper<SysLazyToolUser>().eq(SysLazyToolUser::getMobile, mobile));
        Assert.isTrue(sysLazyToolUser.getEmail().equals(email), "您注册绑定的邮箱与【%s】不一样，找回密码失败".formatted(email));
        String pwd = sysLazyToolUser.getPassword();
        // 通过Email发送密码给用户
        String content = "<h1>尊敬的懒人秘籍用户，您的账号密码是：%s。请注意保管！</h1>".formatted(pwd);
        MailUtils.sendHTMLMail(javaMailSender, fromMail, sysLazyToolUser.getEmail(), SystemConstants.FIND_PWD, content);
    }

    @Override
    public boolean checkIsTestAccount(Long userId) {
        // 检查手机号码绑定的邮箱是否正确
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectById(userId);
        return InnerAccountEnum.Y.getValue().equals(sysLazyToolUser.getInnerStatus());
    }

    @Override
    public void changeStatus(Long userId) {
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectById(userId);
        if (InnerAccountEnum.Y.getValue().equals(sysLazyToolUser.getInnerStatus())) {
            sysLazyToolUser.setInnerStatus(InnerAccountEnum.N.getValue());
        } else {
            sysLazyToolUser.setInnerStatus(InnerAccountEnum.Y.getValue());
        }
        this.saveOrUpdate(sysLazyToolUser);
    }

    @Override
    public boolean changeUserStatus(Long userId) {
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectById(userId);
        if (LazyUserLockStatusEnum.N.getValue().equals(sysLazyToolUser.getLockStatus())) {
            sysLazyToolUser.setLockStatus(LazyUserLockStatusEnum.Y.getValue());
        } else {
            sysLazyToolUser.setLockStatus(LazyUserLockStatusEnum.N.getValue());
        }
        return this.saveOrUpdate(sysLazyToolUser);
    }

    @Override
    public String getPwd(Long userId) {
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectById(userId);
        return sysLazyToolUser.getPassword();
    }

    @Override
    public void updatePwd(String userId, String newPwd, String deviceId) {
        SysLazyToolUser sysLazyToolUser = this.baseMapper.selectById(userId);
        Assert.isTrue(deviceId.equals(sysLazyToolUser.getDeviceId()), "账号已在其他设备登录或者用户未登录，请重新登录");
        sysLazyToolUser.setPassword(newPwd);
        this.saveOrUpdate(sysLazyToolUser);
    }
}
